package com.tangding.shiro.support.redis;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.tangding.common.logx.LogHelp;
import com.tangding.shiro.support.redis.cache.RedisFstSerializer;
import com.tangding.shiro.support.redis.cache.RedisJsonSerializer;


@Component
public class RedisCacheManager implements CacheManager {

	// fast lookup by name map
	@SuppressWarnings("rawtypes")
	private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		LogHelp.doLogApp("获取名称为: " + name + " 的RedisCache实例");
		
		name = getSimpleName(name);
		Cache c = caches.get(name);

		if (c == null) {
			// create a new cache instance
			if (name.indexOf("authorizationCache") != -1) {
				c = new RedisJsonSerializer<String, SimpleAuthorizationInfo>(name, SimpleAuthorizationInfo.class);
			}else if (name.indexOf("authenticationCache") != -1) {
				c = new RedisFstSerializer<String, SimpleAuthenticationInfo>(name, SimpleAuthenticationInfo.class);
			}else {
				c = new RedisFstSerializer<String, String>(name, String.class);
			}

			// add it to the cache collection
			caches.put(name, c);
		}
		return c;
	}
	
	private String getSimpleName(String name) {
		return name.substring(name.lastIndexOf(".") + 1) + "_";
	}
}